<template>
    <!-- 打印预览弹窗 -->
    <div class="preview-box">
      <div
        class="print-btn"
        style="text-align: center; margin-top: 100px;"
      >
        <el-button type="primary" @click="printNotice">打印</el-button>
        <el-button @click="closePreview">关闭</el-button>
        <el-button type="primary" @click="exportExcel">導出</el-button>
      </div>
      <div id="myPrint">
        <slot></slot>
      </div>
    </div>
  </template>
  
  <script>
  import { reactive, toRefs, onMounted, onBeforeUnmount } from "vue";
  import { emitter } from '@/utils/bus.js'
  import printJS from "print-js";
  import { useBtnAuth } from "@/utils/btnAuth";
  export default {
    props: ["printStyle"],
    setup(props, ct5) {
      const state = reactive({
        count: 0,
      });
      const btnAuth = useBtnAuth();
      let printStatus = 0
      function printNotice(params) {
        printJS({
          printable: "myPrint", // 标签元素id
          type: "html",
          header: "",
          targetStyle: "*",
          targetStyles: "*",
          scanStyles: false,
          style: props.printStyle,
          documentTitle: "　",
        });
      }
  
      function reprint(event) {
          if (event.ctrlKey && event.key === "p") {
            printNotice();
            // 阻止默认行为，例如打印页面
            event.preventDefault();
          }
      }
  
      function closePreview(params) {
        ct5.emit("closePreview");
      }
  
      function exportExcel(params) {
          ct5.emit("print");
      }
  
      onMounted(() => {
        window.addEventListener("keydown", reprint);
      });
      onBeforeUnmount(() => {
        window.removeEventListener("keydown", reprint);
        if(printStatus==1) {
          emitter.emit("reload");
        }
      });
  
      return {
        ...toRefs(state),
        printNotice,
        exportExcel,
        closePreview,
        btnAuth
      };
    },
  };
  </script>
  
  <style lang="scss" scoped>
  .preview-box {
    position: fixed;
    top: 0;
    right: 0;
    left: 0;
    bottom: 0;
    z-index: 1002;
    background-color: #fff;
    padding: 20px;
    overflow: auto;
    .print-btn {
      position: fixed;
      top: -80px;
    }
  }
  </style>
  